package conversion.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import conversion.bean.User;
import conversion.utils.JwtUtils;
import conversion.vo.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Component
public class LoginSuccessHandle implements AuthenticationSuccessHandler {

    @Resource
    JwtUtils jwtUtils;

    @Resource
    ObjectMapper objectMapper;

    /**
     * 注入redisTemplate用于缓存数据
     */
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        //从认证信息里获取用户信息
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        User user = securityUser.getUser();
        String userInfo = objectMapper.writeValueAsString(user);

        List<GrantedAuthority> authorities = (List<GrantedAuthority>)securityUser.getAuthorities();

        List<String> authList = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        String token = jwtUtils.createToken(userInfo, authList);

//        response.setHeader("Authorization", "Bearer " + token);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(1000 * 60 * 60 * 24);  // 设置 cookie 的生命周期（单位：秒），这里设置为 一天
        cookie.setPath("/");  // 设置 cookie 的路径
//        HttpSession session = request.getSession();
//        session.setAttribute("user",user);

        response.addCookie(cookie);

        redisTemplate.opsForValue().set("token",token,12, TimeUnit.HOURS);

        log.info("登录成功");
        // 设置响应体的内容类型为 JSON
        response.setContentType("application/json");

        // 创建要放置在响应体中的数据
        String data = "{\"msg\":\"登录成功\"}";

        // 将数据写入响应体
        response.getWriter().write(data);
    }

}
